<template>
  <div id="login">
    <div class="card">
      <el-card class="box-card">
        <h3 class="title">后台管理系统</h3>
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item prop="username">
            <el-input placeholder="账号" v-model="form.username">
              <i slot="prefix" class="el-input__icon el-icon-user"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" placeholder="密码" v-model="form.password">
              <i slot="prefix" class="el-input__icon el-icon-lock"></i>
            </el-input>
          </el-form-item>
          <el-row :gutter="50" class="btn">
            <el-col :span="12">
              <el-button type="info" @click="cz">重置</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="primary" @click="dl">登录</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { login } from "@/api/index";
import { setToken } from "@/utils/token";
export default {
  name: 'login',
  data() {
    return {
      form: {
        type: 1,
        username: 'admin',
        password: '123456',
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  mounted() {

  },
  methods: {
    cz() {
      this.$refs.form.resetFields();
    },
    dl() {
      login(this.form).then((res) => {
        if (!res.data.status) {
          this.$message.error('登录失败')
          return
        }
        //保存token
        setToken(res.data.token)
        //保存登录信息
        let userinfo = {
          username: this.form.username,
          state: true,
        }
        this.$cache.local.setJSON('userinfo', userinfo)
        //路由有重定向= >去重定向页面
        if (this.$route.query.path) {
          this.$router.replace(this.$route.query.path)
        } else {
          this.$router.replace('/home')
        }
      })
    },
  }
}
</script>

<style lang="less" src="./index.less" scoped></style>